package com.yicong.ants.view;

import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.cchao.simplelib.view.itemdecoration.GridOffsetsItemDecoration;

/**
 * @author cchao
 * @version 2019-08-06.
 */
public class GridOffsetItemDecoration extends GridOffsetsItemDecoration {
    boolean mHideFirstRowTopOffset = false;

    public GridOffsetItemDecoration(int orientation) {
        super(orientation);
    }

    public GridOffsetItemDecoration setHideFirstRowTopOffset(boolean hideFirstRowTopOffset) {
        mHideFirstRowTopOffset = hideFirstRowTopOffset;
        return this;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int adapterPosition = parent.getChildAdapterPosition(view);
        if (adapterPosition < getSpanCount(parent)) {
            outRect.top = 0;
        }
    }


    private int getSpanCount(RecyclerView parent) {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();

        if (layoutManager instanceof GridLayoutManager) {
            return ((GridLayoutManager) layoutManager).getSpanCount();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            return ((StaggeredGridLayoutManager) layoutManager).getSpanCount();
        } else {
            throw new UnsupportedOperationException("the GridDividerItemDecoration can only be used in " +
                "the RecyclerView which use a GridLayoutManager or StaggeredGridLayoutManager");
        }
    }
}
